#include "IOPFSFileAttached.h"
#include "include/ILog.h"
#include <string.h>
#ifdef __COMPILE_LINUX__
#include <stdio.h>
#endif

CIOPFSFileAttached::CIOPFSFileAttached(stringc dir,stringc filename,CFileSystem *fsp):CIOPFSFileDisk(dir,filename,fsp)
{
}

CIOPFSFileAttached::~CIOPFSFileAttached()
{
}

bool CIOPFSFileAttached::OpenFileForWriting(stringc Name)
{
	if (IsDirectoryString(fd.CompleteName))
	{

	}
	else
	{
		FileBuffer = fopen(fd.CompleteName.c_str(),"wb");
	}

	if (FileBuffer)
	{
		fd.Size = 0;
		fd.FileNameOnly = Name;
		fd.IsDirectory = IsDirectoryString(fd.CompleteName);
		fd.IsLoaded = false;

		stringc StrTemp = "u8 Data[] = {\n";
		u8 *BufferBegin = (u8*)(StrTemp.c_str());

		fwrite(BufferBegin,StrTemp.size(),1,FileBuffer);
//		WriteBinary((void*)BufferBegin,StrTemp.length());
		return true;
	}
	else
	{
		return false;
	}

	return false;
}

u32 CIOPFSFileAttached::WriteBinary(void *Buffer,u32 Size)
{
	if (FileBuffer)
	{
		u8 *TempBuffer = (u8*)Buffer;
		for (u32 i=0;i<Size;i++)
			DataBuffer.push_back(TempBuffer[i]);

		return Size;
	}
	return 0;
}

bool CIOPFSFileAttached::CloseFile()
{
	pLogDebug << "CIOPFSFileAttached:: Writing everything...\n";
	u32 Counter = 0;
	for (u32 i=0;i<DataBuffer.size();i++)
	{
		char Cad[10];
		sprintf(Cad,"%u",DataBuffer[i]);
		if (i< (DataBuffer.size() - 1))
			strcat(Cad,",");
		else
			strcat(Cad,"};\n");

		fwrite(Cad,strlen(Cad),1,FileBuffer);
		Counter++;

		if (Counter > 40)
		{
			strcpy(Cad,"\n");
			fwrite(Cad,strlen(Cad),1,FileBuffer);
			Counter = 0;
		}
	}
	fclose(FileBuffer);
	FileBuffer = NULL;
	DataBuffer.clear();
	pLogDebug << "CIOPFSFileAttached: Everything wroted\n";
	return true;
}

bool CIOPFSFileAttached::GetAttachedFile(stringc FileName,u32 *Result)
{
	for (u32 i=0;i<fs->GetAttachedFileSystems().size();i++)
	{
		if (fs->GetAttachedFileSystems()[i]->PFSFileName == FileName)
		{
			(*Result) = i;
			return true;
		}
	}

	(*Result) = 0;
	return false;

}

s32 CIOPFSFileAttached::FRead(void *Buffer,u32 Size,void *BufferFrom)
{
	u8 *Buf = (u8*)BufferFrom;
	memcpy(Buffer,Buf+IndexFile,Size);
	IndexFile += Size;
	return Size;
}

s32 CIOPFSFileAttached::FClose(void *BufferToClose)
{
	fs->GetAttachedFileSystems()[ActualFile]->Readed = true;
	fs->GetAttachedFileSystems()[ActualFile]->FilePointer = 0;
	return 0;
}

s32 CIOPFSFileAttached::FSeek(void *Buffer,u32 PositionToSeek)
{
	IndexFile = PositionToSeek;
	return 0;
}

void *CIOPFSFileAttached::FOpenReadBinary(stringc FileToOpen)
{
	u32 Result=0;
	if (GetAttachedFile(FileToOpen,&Result))
	{
		ActualFile = Result;
		fs->GetAttachedFileSystems()[ActualFile]->FilePointer = 0;
		IndexFile = Result;
		return fs->GetAttachedFileSystems()[ActualFile]->Data;
	}

	return NULL;

}
